package com.start.mc;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

public class MyRequest {

    public String get(String url1, Map<String, String> headers) {
        HttpURLConnection connection = null;
        try {
            URL url = new URL(url1);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(3000);
            connection.setReadTimeout(3000);

            // 设置请求头
            if (headers != null) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    connection.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }

            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                try (InputStream inputStream = connection.getInputStream();
                     ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream()) {
                    byte[] buffer = new byte[1024];
                    int length;
                    while ((length = inputStream.read(buffer)) != -1) {
                        arrayOutputStream.write(buffer, 0, length);
                    }
                    String raw = new String(arrayOutputStream.toByteArray(), "UTF-8");
//                    String raw = arrayOutputStream.toString(StandardCharsets.UTF_8);
                    return unicodeToString(raw); // ⚡ 在这里转义
                }
            }
            return "-1";
        } catch (Exception e) {
            e.printStackTrace();
            return "-1";
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }
    /**
     * 把 \\uXXXX 转成中文
     */
    private static String unicodeToString(String unicode) {
        StringBuilder sb = new StringBuilder();
        int i = 0;
        while (i < unicode.length()) {
            if (unicode.charAt(i) == '\\' && i + 1 < unicode.length() && unicode.charAt(i + 1) == 'u') {
                try {
                    String hex = unicode.substring(i + 2, i + 6);
                    sb.append((char) Integer.parseInt(hex, 16));
                    i += 6;
                } catch (Exception e) {
                    sb.append(unicode.charAt(i));
                    i++;
                }
            } else {
                sb.append(unicode.charAt(i));
                i++;
            }
        }
        return sb.toString();
    }
}
